import { Link, useHistory } from 'react-router-dom'
import {
  Card,
  Breadcrumb,
  Form,
  Button,
  Radio,
  DatePicker,
  Table,
  Tag,
  Space,
  Modal,
} from 'antd'
import { Channel } from '@/components/Channel'
import img404 from '@/assets/images/error.png'
import {
  EditOutlined,
  DeleteOutlined,
  ExclamationCircleOutlined,
} from '@ant-design/icons'
import { useEffect, useRef } from 'react'
import { useDispatch, useSelector } from 'react-redux'
import { getArticles, delArticle } from '@/store/actions'
const { RangePicker } = DatePicker
const { confirm } = Modal
const articleState = {
  0: { color: 'yellow', text: '草稿' },
  1: { color: '#ccc', text: '待审核' },
  2: { color: 'green', text: '审核通过' },
  3: { color: 'red', text: '审核失败' },
}

const Article = () => {
  const dispatch = useDispatch()
  const history = useHistory()
  const paramsRef = useRef({})
  const { page, pageSize, list, count } = useSelector((state) => state.article)
  useEffect(() => {
    dispatch(getArticles({}))
  }, [dispatch])

  // 删除文章
  const deleteItem = (id) => {
    confirm({
      title: '温馨提示!',
      icon: <ExclamationCircleOutlined />,
      content: '该操作不可逆,你确定要删除吗?',
      // 第一种：
      onOk() {
        dispatch(delArticle(id, paramsRef.current))
      },
      // 第二种：
      // async onOk() {
      //  await dispatch(delArticle(id))
      //  await dispatch(getArticles(paramsRef.current))
      // },
    })
  }

  // 页数和条数改变
  const onChange = (page, pageSize) => {
    console.log(page, pageSize)
    const params = {
      ...paramsRef.current,
      page,
      per_page: pageSize,
    }

    paramsRef.current = params
    dispatch(getArticles(params))
  }
  // 筛选
  const onSearch = (values) => {
    console.log(values)
    const { status, date, channel_id } = values
    const params = {}
    if (status !== -1) {
      params.status = status
    }
    if (channel_id !== undefined) {
      params.channel_id = channel_id
    }
    if (date !== undefined && date !== null) {
      params.begin_pubdate = date[0].format('YYYY-MM-DD HH:ss:mm')
      params.end_pubdate = date[1].format('YYYY-MM-DD HH:ss:mm')
    }
    console.log(params)

    paramsRef.current = params

    dispatch(getArticles(params))
  }
  const columns = [
    {
      title: '封面',
      dataIndex: 'cover',
      render: (cover) => {
        return <img src={cover ?? img404} width={200} height={150} alt="" />
      },
    },
    {
      title: '标题',
      dataIndex: 'title',
      width: 220,
    },
    {
      title: '状态',
      dataIndex: 'status',
      render: (status) => {
        return (
          <Tag color={articleState[status].color}>
            {articleState[status].text}
          </Tag>
        )
      },
    },
    {
      title: '发布时间',
      dataIndex: 'pubdate',
    },
    {
      title: '阅读数',
      dataIndex: 'read_count',
    },
    {
      title: '评论数',
      dataIndex: 'comment_count',
    },
    {
      title: '点赞数',
      dataIndex: 'like_count',
    },
    {
      title: '操作',
      render: (data) => {
        return (
          <Space size="middle">
            <Button
              type="primary"
              shape="circle"
              icon={<EditOutlined />}
              onClick={() => history.push(`/home/publish/${data.id}`)}
            />
            <Button
              type="primary"
              danger
              shape="circle"
              icon={<DeleteOutlined />}
              onClick={() => deleteItem(data.id)}
            />
          </Space>
        )
      },
    },
  ]

  return (
    <div>
      <Card
        title={
          <Breadcrumb separator=">">
            <Breadcrumb.Item>
              <Link to="/home">首页</Link>
            </Breadcrumb.Item>
            <Breadcrumb.Item>内容管理</Breadcrumb.Item>
          </Breadcrumb>
        }
        style={{ marginBottom: 20 }}
      >
        <Form initialValues={{ status: -1 }} onFinish={onSearch}>
          <Form.Item label="状态" name="status">
            <Radio.Group>
              <Radio value={-1}>全部</Radio>
              <Radio value={0}>草稿</Radio>
              <Radio value={1}>待审核</Radio>
              <Radio value={2}>审核通过</Radio>
              <Radio value={3}>审核失败</Radio>
            </Radio.Group>
          </Form.Item>

          <Form.Item label="频道" name="channel_id">
            <Channel width={288}></Channel>
          </Form.Item>

          <Form.Item label="日期" name="date">
            <RangePicker></RangePicker>
          </Form.Item>

          <Form.Item>
            <Button type="primary" htmlType="submit">
              筛选
            </Button>
          </Form.Item>
        </Form>
      </Card>

      <Card title={`根据筛选条件共查询到${count}条结果`}>
        <Table
          rowKey="id"
          columns={columns}
          dataSource={list}
          pagination={{
            current: page,
            pageSize,
            total: count,
            showSizeChanger: true,
            position: ['bottomCenter'],
            onChange: onChange,
          }}
        />
      </Card>
    </div>
  )
}

export default Article
